class HeatBathDemon extends Demon
{
	HeatBathDemon(Lattice lattice)
	{
		super(lattice);
	}
	void flip(float temperature,float magneticfield,int n)
	{
		int x,y;
		x=y=0;
		float energy,epos=0;
		for(int i=0;i<n;i++)
		{
			x=(int)Math.floor(Math.random()*_lattice.getLength());
			y=(int)Math.floor(Math.random()*_lattice.getWidth());
			_lattice.getArray()[x][y]=1;
			energy=_lattice.getOneSpinEnergy(x,y,magneticfield);
			epos=(float)Math.exp(-1*energy/temperature);
			epos=epos/(epos+1/epos);
			if(Math.random()>epos) _lattice.getArray()[x][y]=-1;
		}
	}
	void interact(float temperature,float magneticfield)
	{
		_finished=true;
		long spin=_lattice.getSpin();
		for(int i=0;i<Math.sqrt(_lattice.getSize());i++)
		{
			flip(temperature,magneticfield,(int)Math.sqrt(_lattice.getSize()));
			if(Math.abs(spin-_lattice.getSpin())>Math.sqrt(_lattice.getSize()))
				_finished=false;
		}
	}
}
class HeatBathEngine extends Engine
{
	HeatBathEngine(Lattice lattice)
	{
		super(lattice);
		_demons.add(new HeatBathDemon(lattice));
	}
}
